<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数字跳动</title>
</head>

<style>
  h1 {
    font-size: 150px;
    text-align: center;
  }

  p {
    text-align: center;
  }

  button {
    font-size: 40px;
  }
</style>

<body>
<h1 id="h1"></h1>
<p></p>
<button onclick="start()">开始</button>
</body>

<script>
  /*

* startNum 代表要跳动的初始数字

* targetNum 代表要跳动到的数字

* time 代表要跳动需要花费的时间

* selector 代表要跳动元素的选择器

*/

  const $setJumpNumber = (startNum, targetNum, time = 1, selector) => {
    let dom = document.querySelector(selector);
    let originNum = startNum;
    let stepNum = 0;
    let timeNum = time;
    dom.innerHTML = startNum;
    let timeId = setInterval(() => {
      if (originNum < targetNum) {
        timeNum -= 0.001;
        let strNum = originNum.toString();
        // 数字比较少的时候直接用 + 1; 数字很大直接 +1 要很久才能调到最对应的数字，所有后三位数随机跳动的方式进行模拟生成
        if (targetNum.toString().length < 6) {
          stepNum += 1; // 这样才可以实现越跳越快的效果
          originNum = originNum + stepNum;
          dom.innerHTML = originNum;
        } else {
          stepNum += 500; // 这样才可以实现越跳越快的效果
          originNum = originNum + stepNum;
          dom.innerHTML = strNum.substr(0, strNum.length - 3) + Math.floor(Math.random() * 10) + Math.floor(Math
            .random() * 10) + Math.floor(Math.random() * 10);
        }
      } else {
        dom.innerHTML = targetNum;
        clearInterval(timeId);
      }
    }, timeNum);
  };

  function start() {
    $setJumpNumber(11, 218983423, 1, 'h1');
  };
</script>

</html>